import axios from 'axios';
import bean from '../beans';
import { Loading, Message } from 'element-ui';

class BaseService {
  private axios: any = null;
  private reqCount: number = 0;
  private loading: any = null;

  constructor() {
    this.axios.defaults.timeout = 45000;

    axios.interceptors.request.use((config: any) => {
      if (this.reqCount === 0) {
        this.loading = Loading.service(bean.loading);
      }
      this.reqCount++;
      return config;
    }, (error: any) => {
      this.reqCount--;
      if (this.reqCount === 0) {
        setTimeout(() => {
          this.loading.close();
        }, 300);
      }
      Message({
        message: '加载超时',
        type: 'error',
      });
      return Promise.reject(error);
    });
  }

  public get(str: string, data: object, resolve: any) {
    this.axios.get(str, {
      params: data || {},
    }).then((res: any) => {
      if (res.status === 200 && res.data.status === 0) {
        resolve(res.data);
      } else {
        resolve(res.data || {
          status: 1,
          msg: '请求失败',
        });
      }
    });
  }

  public delete(str: string, data: object, resolve: any) {
    this.axios.delete(str, {
      params: data || {},
    }).then((res: any) => {
      if (res.status === 200 && res.data.status === 0) {
        resolve(res.data);
      } else {
        resolve(res.data || {
          status: 1,
          msg: '请求失败',
        });
      }
    });
  }

  public post(str: any, data: object, resolve: any) {
    this.axios.post(str, data).then((res: any) => {
      if (res.status === 200 && res.data.status === 0) {
        resolve(res.data);
      } else {
        resolve(res.data || {
          status: 1,
          msg: '请求失败',
        });
      }
    });
  }

  public put(str: string, data: object, resolve: any) {
    this.axios.put(str, data).then((res: any) => {
      if (res.status === 200 && res.data.status === 0) {
        resolve(res.data);
      } else {
        resolve(res.data || {
          status: 1,
          msg: '请求失败',
        });
      }
    });
  }
}

export default new BaseService();
